package org.doubango.imsdroid.Login;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


import org.doubango.imsdroid.R;
import org.doubango.imsdroid.Screens.BaseScreen;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by TaZ on 2017/11/17.
 */

public class RegisterActivity extends BaseScreen {

    private EditText et_user;
    private EditText et_pwd;
    private EditText et_again;
    private Button btn;
    private static String TAG = RegisterActivity.class.getCanonicalName();
    private static String sip_remark;
    private static String back_results = null;

    final OkHttpClient client = new OkHttpClient();

    @SuppressWarnings("Handlerleak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                String json = (String) msg.obj;
                Log.i("Response", json);
                parseJSONWithJSONObject(json);
                if (back_results.equals("true")) {
                    Toast.makeText(RegisterActivity.this, "注册成功！", Toast.LENGTH_SHORT).show();
                    finish();
                } else if (back_results.equals("false")) {
                    Toast.makeText(RegisterActivity.this, "用户已注册！", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    protected RegisterActivity() {
        super(SCREEN_TYPE.REGISTER_T, TAG);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);

        et_user = (EditText) findViewById(R.id.register_username);
        et_pwd = (EditText) findViewById(R.id.register_psw);
        et_again = (EditText) findViewById(R.id.register_re_psw);
        btn = (Button) findViewById(R.id.register_button);

        //为btn添加监听器
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String username = et_user.getText().toString().trim();
                String pwd = et_pwd.getText().toString().trim();
                String again = et_again.getText().toString().trim();

                if (username.equals("")) {
                    Toast.makeText(RegisterActivity.this,
                            "用户名为空", Toast.LENGTH_SHORT).show();
                    return;
                } else if (pwd.equals("")) {
                    Toast.makeText(RegisterActivity.this,
                            "密码为空", Toast.LENGTH_SHORT).show();
                    return;
                } else if (!pwd.equals(again)) {
                    Toast.makeText(RegisterActivity.this,
                            "两次输入密码不一致", Toast.LENGTH_SHORT).show();
                    return;
                }

                //通过okhttp发起post请求
                postRequest(username, pwd);


            }
        });
    }

    /**
     * post请求后台
     *
     * @param name
     * @param pwd
     */
    private void postRequest(String name, String pwd) {

        //建立请求表单，添加上传服务器的参数
        RequestBody formBody = new FormBody.Builder()
                .add("userName", name)
                .add("loginPwd", pwd)
                .add("method", "okhttpreg")
                .build();

        //发起请求
        final Request request = new Request.Builder()
                .url("http://59.110.217.175:8080/b/register.action?")
                .post(formBody)
                .build();

        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //OkHttpClient client = new OkHttpClient();
                    //回调
                    response = client.newCall(request).execute();
                    String responseData = response.body().string();

                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        mHandler.obtainMessage(1, responseData).sendToTarget();
                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //{ "result" : "registered successfully", "uid" : "2ab5b5deb19f4aee91e04e80039668f2" }
    private void parseJSONWithJSONObject(String jsonData) {
        try {
            Log.d("RegisterActivity", jsonData);
            //将json字符串jsonData装入JSON数组，即JSONArray
            //jsonData可以是从文件中读取，也可以从服务器端获得
            JSONObject jsonObject = new JSONObject(jsonData);

            //循环遍历，依次取出JSONObject对象
            //用getInt和getString方法取出对应键值
            String remark = jsonObject.getString("remark");
            String results = jsonObject.getString("result");


            sip_remark = remark;
            back_results = results;


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
